package com.hzit.web.controller;

import com.hzit.net.SecurityKitUtil;
import com.hzit.web.bean.ImageMsg;
import com.hzit.web.bean.ImageMstItem;
import com.hzit.web.bean.MsgType;
import com.hzit.web.bean.TextMsg;
import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
public class MessageController {


    //页面配置的随机数
    private String mytoken = "bj2004_my_token_xxx";

    @GetMapping("/message")
    @ResponseBody
    public String message(String signature, String timestamp, String nonce, String echostr) {

        //1）将token、timestamp、nonce三个参数进行字典序排序
        String[] strArr = {mytoken, timestamp, nonce};
        //排序
        Arrays.sort(strArr);

        //2）将三个参数字符串拼接成一个字符串进行sha1加密
        StringBuffer sbf = new StringBuffer();
        for (String s : strArr) {
            sbf.append(s);
        }

        String sha1 = SecurityKitUtil.sha1(sbf.toString());


        //3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        if (signature.equals(sha1)) {

            //4) 若确认此次GET请求来自微信服务器，请原样返回echostr参数内容

            return echostr;
        }

        return null;
    }


    @PostMapping("/message")
    @ResponseBody
    public Object message(HttpServletRequest request) throws IOException {

//        ServletInputStream inputStream = request.getInputStream();
//
//        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
//
//        String temp = null;
//        while ((temp = bufferedReader.readLine()) != null) {
//            System.out.println(temp);
//        }

        String msg = autoSendMsg(request);
        return msg;
    }


    /**
     * 处理消息业务逻辑
     *
     * @param request
     * @return
     */
    private String autoSendMsg(HttpServletRequest request) throws IOException {

        //业务：文本,人工智能    图片：喜欢我么   其他类似:正在开发中    任务:石头剪布

        //1.获取用户发送的xml
        ServletInputStream inputStream = request.getInputStream();


        //2.提取出 需要的数据
        Map<String, String> revMsg = getMessageInfo(inputStream);
        String msgType = revMsg.get("msgType");
        String toUser = revMsg.get("toUserName");
        String fromUser = revMsg.get("fromUserName");


        //3.判断是否是我们支持的类型
        if (MsgType.MSG_TYPE_TEXT.equals(msgType)) {
            //回复文本消息
            String content = revMsg.get("content");
            content = (content != null && content.trim().length() > 0) ? content : "换一个关键字!";
            String msg = this.sendTextMsg(fromUser, toUser, content);
            return msg;
        } else if (MsgType.MSG_TYPE_IMAGE.equals(msgType)) {
            //图片消息
            String mediaId = "n3Tpy0o6x-B4bb5jK6uuK1UFrccx9L8hShuAyz-nf5edX4px6KkzuKQVKuIuC0CN";
            String msg = this.sendImageMsg(fromUser, toUser, mediaId);
            return msg;
        } else {
            //正在开发 消息
            String msg = this.sendTextMsg(fromUser, toUser, "正在开发中...,暂支持：文本和图片");
            return msg;
        }

    }

    /**
     * 转换
     *
     * @param inputStream
     * @return
     */
    private Map<String, String> getMessageInfo(InputStream inputStream) {

        try {
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(inputStream);
            Element root = document.getRootElement();

            String toUserName = root.elementText("ToUserName");
            String fromUserName = root.elementText("FromUserName");
            String msgType = root.elementText("MsgType");

            Map<String, String> map = new HashMap<>();
            map.put("toUserName", toUserName);
            map.put("fromUserName", fromUserName);
            map.put("msgType", msgType);

            //额外处理
            //1.如果是文本类型 获取接收到文本的内容
            if ("text".equals(msgType)) {
                String content = root.elementText("Content");
                map.put("content", content);
            }

            return map;
        } catch (Exception e) {

        }

        return null;
    }

    /**
     * 回复文本类型
     *
     * @param toUser
     * @param fromUser
     * @param content
     * @return
     */
    private String sendTextMsg(String toUser, String fromUser, String content) {


        TextMsg textMsg = new TextMsg();
        textMsg.setToUserName(toUser);
        textMsg.setFromUserName(fromUser);
        textMsg.setMsgType(MsgType.MSG_TYPE_TEXT);
        textMsg.setCreateTime(new Date().getTime());

        //人工智能
        content = content.replace("吗", "");
        content = content.replace("我", "我也");
        content = content.replace("?", "!");
        content = content.replace("？", "!");


        textMsg.setContent(content);

        //对象转为xml文件
        XStream xStream = new XStream();
        xStream.alias("xml", TextMsg.class);
        String s = xStream.toXML(textMsg);

        System.out.println("回复文本消息:" + s);
        return s;
    }


    /**
     * 回复图片消息
     *
     * @param toUser
     * @param fromUser
     * @param mediaId
     * @return
     */
    private String sendImageMsg(String toUser, String fromUser, String mediaId) {

        ImageMsg imageMsg = new ImageMsg();
        imageMsg.setToUserName(toUser);
        imageMsg.setFromUserName(fromUser);
        imageMsg.setMsgType(MsgType.MSG_TYPE_IMAGE);
        imageMsg.setCreateTime(new Date().getTime());

        ImageMstItem imageItem = new ImageMstItem();
        imageItem.setMediaId(mediaId);
        imageMsg.setImage(imageItem);

        XStream xStream = new XStream();
        xStream.alias("xml", ImageMsg.class);
        xStream.alias("Image", ImageMstItem.class);

        String xml = xStream.toXML(imageMsg);
        System.out.println("回复图片消息:" + xml);
        return xml;
    }


    private String sendClikc(){

        return null;
    }

}
